<?php

namespace app\api\controller;

use think\facade\Db;
use think\Response;
use app\common\controller\Frontend;

class RoomAudioConfig extends Frontend
{
    protected array $noNeedLogin = [
        'getRoomConfigs', 'updateRoomConfig', 'getRoomAudios', 
        'addAudioToRoom', 'addMultipleAudiosToRoom', 'removeAudioFromRoom', 'updateAudioSort',
        'createRoomCategory', 'deleteRoomCategory', 'updateAudioVolume', 'updateMultipleAudioVolumes'
    ];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 获取房间音频配置
     */
    public function getRoomConfigs(): Response
    {
        $roomId = $this->request->get('room_id', 0);

        if (empty($roomId)) {
            $this->error('房间ID不能为空');
        }

        try {
            // 获取房间配置
            $configs = Db::name('api_room_audio_configs')
                ->where('room_id', $roomId)
                ->where('status', 1)
                ->order('order asc, category_type')
                ->select()
                ->toArray();

            // 如果没有配置，创建默认配置
            if (empty($configs)) {
                $this->createDefaultConfigs($roomId);
                $configs = Db::name('api_room_audio_configs')
                    ->where('room_id', $roomId)
                    ->where('status', 1)
                    ->order('order asc, category_type')
                    ->select()
                    ->toArray();
            }

            // 格式化配置数据
            $result = [];
            foreach ($configs as $config) {
                $result[$config['category_type']] = [
                    'id' => $config['id'],
                    'category_type' => $config['category_type'],
                    'play_mode' => $config['play_mode'],
                    'interval_min' => $config['interval_min'],
                    'interval_max' => $config['interval_max'],
                    'auto_play' => $config['auto_play'],
                    'volume' => floatval($config['volume']),
                    'is_expanded' => $config['is_expanded'],
                    'status' => $config['status'],
                    'order' => intval($config['order'] ?? 0), // 添加排序字段
                    // 添加自定义分类的显示信息（如果有的话）
                    'category_name' => $config['category_name'] ?? null,
                    'description' => $config['description'] ?? null,
                    'icon' => $config['icon'] ?? null,
                    // 添加随机片段播放相关字段
                    'max_concurrent' => intval($config['max_concurrent'] ?? 1),
                    'random_fragment' => intval($config['random_fragment'] ?? 0),
                    'fragment_min_duration' => intval($config['fragment_min_duration'] ?? 3),
                    'fragment_max_duration' => intval($config['fragment_max_duration'] ?? 8),
                    'fragment_probability' => intval($config['fragment_probability'] ?? 35),
                    'fragment_min_audio_length' => intval($config['fragment_min_audio_length'] ?? 15),
                    'fragment_start_strategy' => $config['fragment_start_strategy'] ?? 'avoid_start'
                ];
            }

            $this->success('获取房间配置成功', $result);
        } catch (Exception $e) {
            $this->error('获取房间配置失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新房间音频配置
     */
    public function updateRoomConfig(): Response
    {
        $data = $this->request->post();
        $roomId = $data['room_id'] ?? 0;
        $categoryType = $data['category_type'] ?? '';

        if (empty($roomId)) {
            $this->error('房间ID不能为空');
        }

        if (empty($categoryType)) {
            $this->error('分类类型不能为空');
        }

        try {
            $updateData = [
                'update_time' => time() * 1000,
            ];

            // 更新配置字段
            if (isset($data['play_mode'])) {
                $updateData['play_mode'] = $data['play_mode'];
            }
            if (isset($data['interval_min'])) {
                $updateData['interval_min'] = intval($data['interval_min']);
            }
            if (isset($data['interval_max'])) {
                $updateData['interval_max'] = intval($data['interval_max']);
            }
            if (isset($data['auto_play'])) {
                $updateData['auto_play'] = intval($data['auto_play']);
            }
            if (isset($data['volume'])) {
                $updateData['volume'] = floatval($data['volume']);
            }
            if (isset($data['is_expanded'])) {
                $updateData['is_expanded'] = intval($data['is_expanded']);
            }
            // 添加随机片段播放相关字段的更新支持
            if (isset($data['max_concurrent'])) {
                $updateData['max_concurrent'] = intval($data['max_concurrent']);
            }
            if (isset($data['random_fragment'])) {
                $updateData['random_fragment'] = intval($data['random_fragment']);
            }
            if (isset($data['fragment_min_duration'])) {
                $updateData['fragment_min_duration'] = intval($data['fragment_min_duration']);
            }
            if (isset($data['fragment_max_duration'])) {
                $updateData['fragment_max_duration'] = intval($data['fragment_max_duration']);
            }
            if (isset($data['fragment_probability'])) {
                $updateData['fragment_probability'] = intval($data['fragment_probability']);
            }
            if (isset($data['fragment_min_audio_length'])) {
                $updateData['fragment_min_audio_length'] = intval($data['fragment_min_audio_length']);
            }
            if (isset($data['fragment_start_strategy'])) {
                $updateData['fragment_start_strategy'] = $data['fragment_start_strategy'];
            }

            $result = Db::name('api_room_audio_configs')
                ->where('room_id', $roomId)
                ->where('category_type', $categoryType)
                ->update($updateData);

            if ($result !== false) {
                $this->success('更新配置成功');
            } else {
                $this->error('更新配置失败');
            }
        } catch (Exception $e) {
            $this->error('更新配置失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取房间中的音频列表（按分类组织）
     */
    public function getRoomAudios(): Response
    {
        $roomId = $this->request->get('room_id', 0);

        if (empty($roomId)) {
            $this->error('房间ID不能为空');
        }

        try {
            // 获取房间中的音频关联信息
            $audioRelations = Db::name('api_room_audio_relations')
                ->alias('r')
                ->leftJoin('api_audios a', 'r.audio_id = a.id')
                ->where('r.room_id', $roomId)
                ->where('r.is_active', 1)
                ->where('a.status', 1)
                ->field('r.*, a.name, a.display_name, a.duration, a.file_path, a.format')
                ->order('r.category_type, r.sort_order')
                ->select()
                ->toArray();

            // 动态按分类组织数据
            $result = [];

            foreach ($audioRelations as $relation) {
                $audioData = [
                    'relation_id' => $relation['id'],
                    'audio_id' => $relation['audio_id'],
                    'name' => $relation['name'],
                    'display_name' => $relation['display_name'],
                    'duration' => $relation['duration'],
                    'file_path' => $relation['file_path'],
                    'format' => $relation['format'],
                    'category_type' => $relation['category_type'],
                    'sub_category' => $relation['sub_category'],
                    'sort_order' => $relation['sort_order'],
                    'volume' => floatval($relation['volume'])
                ];

                // 如果分类不存在，创建空数组
                if (!isset($result[$relation['category_type']])) {
                    $result[$relation['category_type']] = [];
                }
                
                $result[$relation['category_type']][] = $audioData;
            }

            // 确保基本分类存在（即使为空）
            $defaultCategories = ['scene', 'background', 'other'];
            foreach ($defaultCategories as $category) {
                if (!isset($result[$category])) {
                    $result[$category] = [];
                }
            }

            $this->success('获取房间音频列表成功', $result);
        } catch (Exception $e) {
            $this->error('获取房间音频列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 添加音频到房间分类
     */
    public function addAudioToRoom(): Response
    {
        $data = $this->request->post();
        $roomId = $data['room_id'] ?? 0;
        $audioId = $data['audio_id'] ?? 0;
        $categoryType = $data['category_type'] ?? '';
        $subCategory = $data['sub_category'] ?? null;

        if (empty($roomId) || empty($audioId) || empty($categoryType)) {
            $this->error('房间ID、音频ID和分类类型不能为空');
        }

        try {
            // 检查是否已存在
            $exists = Db::name('api_room_audio_relations')
                ->where('room_id', $roomId)
                ->where('audio_id', $audioId)
                ->where('category_type', $categoryType)
                ->find();

            if ($exists) {
                $this->error('该音频已在此分类中');
            }

            // 获取当前分类中的最大排序值
            $maxSort = Db::name('api_room_audio_relations')
                ->where('room_id', $roomId)
                ->where('category_type', $categoryType)
                ->max('sort_order');

            $insertData = [
                'room_id' => $roomId,
                'audio_id' => $audioId,
                'category_type' => $categoryType,
                'sub_category' => $subCategory,
                'sort_order' => ($maxSort ?? 0) + 1,
                'is_active' => 1,
                'create_time' => time() * 1000,
                'update_time' => time() * 1000,
            ];

            $relationId = Db::name('api_room_audio_relations')->insertGetId($insertData);

            if ($relationId) {
                $this->success('添加音频到房间成功', ['relation_id' => $relationId]);
            } else {
                $this->error('添加音频到房间失败');
            }
        } catch (Exception $e) {
            $this->error('添加音频到房间失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量添加音频到房间分类
     */
    public function addMultipleAudiosToRoom(): Response
    {
        $data = $this->request->post();
        $roomId = $data['room_id'] ?? 0;
        $audioIds = $data['audio_ids'] ?? [];
        $categoryType = $data['category_type'] ?? '';
        $subCategory = $data['sub_category'] ?? null;

        if (empty($roomId) || empty($audioIds) || empty($categoryType)) {
            $this->error('房间ID、音频ID列表和分类类型不能为空');
        }

        if (!is_array($audioIds)) {
            $this->error('音频ID列表格式错误');
        }

        try {
            Db::startTrans();
            
            $successCount = 0;
            $existsCount = 0;
            $errorCount = 0;
            $addedRelationIds = [];

            // 获取当前分类中的最大排序值
            $maxSort = Db::name('api_room_audio_relations')
                ->where('room_id', $roomId)
                ->where('category_type', $categoryType)
                ->max('sort_order');
            
            $currentSort = ($maxSort ?? 0);

            foreach ($audioIds as $audioId) {
                try {
                    // 检查是否已存在
                    $exists = Db::name('api_room_audio_relations')
                        ->where('room_id', $roomId)
                        ->where('audio_id', $audioId)
                        ->where('category_type', $categoryType)
                        ->find();

                    if ($exists) {
                        $existsCount++;
                        continue;
                    }

                    // 检查音频是否存在
                    $audioExists = Db::name('api_audios')
                        ->where('id', $audioId)
                        ->where('room_id', $roomId)
                        ->where('status', 1)
                        ->find();
                        
                    if (!$audioExists) {
                        $errorCount++;
                        continue;
                    }

                    $currentSort++;
                    $insertData = [
                        'room_id' => $roomId,
                        'audio_id' => $audioId,
                        'category_type' => $categoryType,
                        'sub_category' => $subCategory,
                        'sort_order' => $currentSort,
                        'is_active' => 1,
                        'create_time' => time() * 1000,
                        'update_time' => time() * 1000,
                    ];

                    $relationId = Db::name('api_room_audio_relations')->insertGetId($insertData);
                    
                    if ($relationId) {
                        $successCount++;
                        $addedRelationIds[] = $relationId;
                    } else {
                        $errorCount++;
                    }
                } catch (Exception $e) {
                    $errorCount++;
                    continue;
                }
            }

            if ($successCount > 0) {
                Db::commit();
                
                $message = "批量添加完成：成功 {$successCount} 个";
                if ($existsCount > 0) {
                    $message .= "，已存在 {$existsCount} 个";
                }
                if ($errorCount > 0) {
                    $message .= "，失败 {$errorCount} 个";
                }

                $this->success($message, [
                    'success_count' => $successCount,
                    'exists_count' => $existsCount,
                    'error_count' => $errorCount,
                    'total_count' => count($audioIds),
                    'added_relation_ids' => $addedRelationIds
                ]);
            } else {
                Db::rollback();
                
                if ($existsCount === count($audioIds)) {
                    $this->error('所选音频已全部在此分类中');
                } else {
                    $this->error('批量添加失败，没有成功添加任何音频');
                }
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('批量添加音频失败: ' . $e->getMessage());
        }
    }

    /**
     * 从房间分类中移除音频
     */
    public function removeAudioFromRoom(): Response
    {
        $relationId = $this->request->post('relation_id', 0);

        if (empty($relationId)) {
            $this->error('关联ID不能为空');
        }

        try {
            $result = Db::name('api_room_audio_relations')
                ->where('id', $relationId)
                ->delete();

            if ($result) {
                $this->success('移除音频成功');
            } else {
                $this->error('移除音频失败');
            }
        } catch (Exception $e) {
            $this->error('移除音频失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新音频排序
     */
    public function updateAudioSort(): Response
    {
        $data = $this->request->post();
        $roomId = $data['room_id'] ?? 0;
        $categoryType = $data['category_type'] ?? '';
        $sortData = $data['sort_data'] ?? [];

        if (empty($roomId) || empty($categoryType) || empty($sortData)) {
            $this->error('参数不完整');
        }

        try {
            Db::startTrans();

            foreach ($sortData as $item) {
                $relationId = $item['relation_id'] ?? 0;
                $sortOrder = $item['sort_order'] ?? 0;

                if ($relationId && $sortOrder >= 0) {
                    Db::name('api_room_audio_relations')
                        ->where('id', $relationId)
                        ->where('room_id', $roomId)
                        ->where('category_type', $categoryType)
                        ->update([
                            'sort_order' => $sortOrder,
                            'update_time' => time() * 1000
                        ]);
                }
            }

            Db::commit();
            $this->success('更新排序成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('更新排序失败: ' . $e->getMessage());
        }
    }

    /**
     * 创建房间分类配置
     */
    public function createRoomCategory(): Response
    {
        $data = $this->request->post();
        $roomId = $data['room_id'] ?? 0;
        $categoryType = $data['category_type'] ?? '';
        $categoryName = $data['category_name'] ?? '';
        $description = $data['description'] ?? '';
        $icon = $data['icon'] ?? '🎵';
        $config = $data['config'] ?? [];

        if (empty($roomId)) {
            $this->error('房间ID不能为空');
        }

        if (empty($categoryType)) {
            $this->error('分类类型不能为空');
        }

        if (empty($categoryName)) {
            $this->error('分类名称不能为空');
        }

        try {
            // 检查分类是否已存在
            $exists = Db::name('api_room_audio_configs')
                ->where('room_id', $roomId)
                ->where('category_type', $categoryType)
                ->find();

            if ($exists) {
                $this->error('该分类已存在');
            }

            // 设置默认配置
            $defaultConfig = [
                'play_mode' => $config['playMode'] ?? 'sequential',
                'interval_min' => $config['intervalMin'] ?? 10,
                'interval_max' => $config['intervalMax'] ?? 30,
                'auto_play' => $config['autoPlay'] ?? false,
                'volume' => $config['volume'] ?? 1.00,
            ];

            // 插入新分类配置
            $insertData = [
                'room_id' => $roomId,
                'category_type' => $categoryType,
                'category_name' => $categoryName,
                'description' => $description,
                'icon' => $icon,
                'play_mode' => $defaultConfig['play_mode'],
                'interval_min' => intval($defaultConfig['interval_min']),
                'interval_max' => intval($defaultConfig['interval_max']),
                'auto_play' => intval($defaultConfig['auto_play']),
                'volume' => floatval($defaultConfig['volume']),
                'is_expanded' => 1,
                'status' => 1,
                'create_time' => time() * 1000,
                'update_time' => time() * 1000,
            ];

            $configId = Db::name('api_room_audio_configs')->insertGetId($insertData);

            if ($configId) {
                // 返回创建的配置信息
                $result = array_merge($insertData, [
                    'id' => $configId,
                    'category_name' => $categoryName,
                    'description' => $description,
                    'icon' => $icon
                ]);

                $this->success('创建分类成功', $result);
            } else {
                $this->error('创建分类失败');
            }
        } catch (Exception $e) {
            $this->error('创建分类失败: ' . $e->getMessage());
        }
    }

    /**
     * 创建默认配置
     */
    private function createDefaultConfigs($roomId)
    {
        $defaultConfigs = [
            [
                'room_id' => $roomId,
                'category_type' => 'scene',
                'play_mode' => 'sequential',
                'interval_min' => 20,
                'interval_max' => 40,
                'auto_play' => 1,
                'volume' => 1.00,
                'is_expanded' => 1,
                'status' => 1,
                'max_concurrent' => 1,
                'random_fragment' => 0,
                'fragment_min_duration' => 3,
                'fragment_max_duration' => 8,
                'fragment_probability' => 35,
                'fragment_min_audio_length' => 15,
                'fragment_start_strategy' => 'avoid_start',
                'create_time' => time() * 1000,
                'update_time' => time() * 1000,
            ],
            [
                'room_id' => $roomId,
                'category_type' => 'background',
                'play_mode' => 'loop',
                'interval_min' => 0,
                'interval_max' => 0,
                'auto_play' => 0,
                'volume' => 0.30,
                'is_expanded' => 1,
                'status' => 1,
                'max_concurrent' => 1,
                'random_fragment' => 0,
                'fragment_min_duration' => 3,
                'fragment_max_duration' => 8,
                'fragment_probability' => 35,
                'fragment_min_audio_length' => 15,
                'fragment_start_strategy' => 'avoid_start',
                'create_time' => time() * 1000,
                'update_time' => time() * 1000,
            ],
            [
                'room_id' => $roomId,
                'category_type' => 'other',
                'play_mode' => 'manual',
                'interval_min' => 5,
                'interval_max' => 15,
                'auto_play' => 0,
                'volume' => 1.00,
                'is_expanded' => 1,
                'status' => 1,
                'max_concurrent' => 1,
                'random_fragment' => 0,
                'fragment_min_duration' => 3,
                'fragment_max_duration' => 8,
                'fragment_probability' => 35,
                'fragment_min_audio_length' => 15,
                'fragment_start_strategy' => 'avoid_start',
                'create_time' => time() * 1000,
                'update_time' => time() * 1000,
            ]
        ];

        Db::name('api_room_audio_configs')->insertAll($defaultConfigs);
    }

    /**
     * 删除房间分类配置
     * POST /api/room_audio_config/deleteRoomCategory
     */
    public function deleteRoomCategory(): Response
    {
        try {
            // 获取请求参数
            $roomId = $this->request->post('room_id');
            $categoryType = $this->request->post('category_type');
            $audioAction = $this->request->post('audio_action', 'move'); // move: 移动到其他音频, delete: 删除音频

            // 参数验证
            if (empty($roomId)) {
                return json([
                    'code' => 400,
                    'message' => '房间ID不能为空'
                ]);
            }

            if (empty($categoryType)) {
                return json([
                    'code' => 400,
                    'message' => '分类类型不能为空'
                ]);
            }

            // 检查分类是否存在
            $config = Db::name('api_room_audio_configs')
                ->where([
                    'room_id' => $roomId,
                    'category_type' => $categoryType
                ])
                ->find();

            if (!$config) {
                return json([
                    'code' => 404,
                    'message' => '分类配置不存在'
                ]);
            }

            // 开启事务
            Db::startTrans();

            try {
                // 处理该分类下的音频
                $categoryAudios = Db::name('api_room_audio_relations')
                    ->where([
                        'room_id' => $roomId,
                        'category_type' => $categoryType
                    ])
                    ->select();

                if ($categoryAudios) {
                    if ($audioAction === 'delete') {
                        // 删除音频关联关系
                        Db::name('api_room_audio_relations')
                            ->where([
                                'room_id' => $roomId,
                                'category_type' => $categoryType
                            ])
                            ->delete();

                        $audioMessage = '删除了 ' . count($categoryAudios) . ' 个音频文件';
                    } else {
                        // 移动到 other 分类
                        Db::name('api_room_audio_relations')
                            ->where([
                                'room_id' => $roomId,
                                'category_type' => $categoryType
                            ])
                            ->update([
                                'category_type' => 'other',
                                'update_time' => time() * 1000
                            ]);

                        $audioMessage = '移动了 ' . count($categoryAudios) . ' 个音频文件到"其他音频"分类';
                    }
                } else {
                    $audioMessage = '该分类下没有音频文件';
                }

                // 删除分类配置
                Db::name('api_room_audio_configs')
                    ->where([
                        'room_id' => $roomId,
                        'category_type' => $categoryType
                    ])
                    ->delete();

                // 提交事务
                Db::commit();

                return json([
                    'code' => 200,
                    'message' => '分类删除成功',
                    'data' => [
                        'deleted_category' => $categoryType,
                        'audio_action' => $audioAction,
                        'audio_message' => $audioMessage,
                        'audio_count' => count($categoryAudios ?? [])
                    ]
                ]);

            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                
                return json([
                    'code' => 500,
                    'message' => '删除分类时发生错误：' . $e->getMessage()
                ]);
            }

        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '系统错误：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新音频音量
     */
    public function updateAudioVolume(): Response
    {
        $data = $this->request->post();
        $relationId = $data['relation_id'] ?? 0;
        $volume = $data['volume'] ?? 1.0;

        if (empty($relationId)) {
            $this->error('关系ID不能为空');
        }

        // 验证音量范围
        if ($volume < 0 || $volume > 1) {
            $this->error('音量值必须在0-1之间');
        }

        try {
            // 检查关系是否存在
            $relation = Db::name('api_room_audio_relations')
                ->where('id', $relationId)
                ->where('is_active', 1)
                ->find();

            if (!$relation) {
                $this->error('音频关系不存在或已禁用');
            }

            // 更新音量
            $result = Db::name('api_room_audio_relations')
                ->where('id', $relationId)
                ->update([
                    'volume' => $volume,
                    'update_time' => time() * 1000
                ]);

            if ($result !== false) {
                $this->success('更新音频音量成功', [
                    'relation_id' => $relationId,
                    'volume' => $volume
                ]);
            } else {
                $this->error('更新音频音量失败');
            }
        } catch (Exception $e) {
            $this->error('更新音频音量失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量更新音频音量
     */
    public function updateMultipleAudioVolumes(): Response
    {
        $data = $this->request->post();
        $volumeData = $data['volume_data'] ?? [];

        if (empty($volumeData) || !is_array($volumeData)) {
            $this->error('音量数据不能为空');
        }

        try {
            Db::startTrans();

            $successCount = 0;
            foreach ($volumeData as $item) {
                $relationId = $item['relation_id'] ?? 0;
                $volume = $item['volume'] ?? 1.0;

                if (!$relationId || $volume < 0 || $volume > 1) {
                    continue; // 跳过无效数据
                }

                $result = Db::name('api_room_audio_relations')
                    ->where('id', $relationId)
                    ->where('is_active', 1)
                    ->update([
                        'volume' => $volume,
                        'update_time' => time() * 1000
                    ]);

                if ($result !== false) {
                    $successCount++;
                }
            }

            Db::commit();
            $this->success('批量更新音频音量成功', [
                'updated_count' => $successCount,
                'total_count' => count($volumeData)
            ]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('批量更新音频音量失败: ' . $e->getMessage());
        }
    }
}
